<template>
  <div class="dh width_max">
    <m-header :title="title" :show="true"></m-header>

    <Form
      class="card_box width_max height_max"
      :model="userdata"
      :rules="ruleValidate"
      :label-width="100"
      ref="form"
      label-position="left"
    >
      <div class="card width_max bg_white buttom">
        <FormItem label="真实姓名：" prop="name">
          <Input v-model="userdata.name" placeholder="不超过10个汉字或20个英文字符"/>
        </FormItem>

        <FormItem label="真实性别：" prop="sex">
          <RadioGroup v-model="userdata.sex">
            <Radio label="男">男</Radio>
            <Radio label="女">女</Radio>
          </RadioGroup>
        </FormItem>

        <FormItem label="出生日期：" prop="Date_of_birth">
          <DatePicker
            v-model="userdata.Date_of_birth"
            format="yyyy年MM月dd日"
            type="date"
            placeholder="请选择时间"
          ></DatePicker>
        </FormItem>

        <FormItem label="身份证号：" prop="ID_No">
          <Input v-model="userdata.ID_No" placeholder="填入18位数身份证号码"/>
        </FormItem>

        <FormItem label="护照号：" prop="Passport_No">
          <Input v-model="userdata.Passport_No" placeholder="填入护照或通行证号码"/>
        </FormItem>

        <FormItem label="证件有效期：" prop="Certificate_validity_period">
          <DatePicker
            v-model="userdata.Certificate_validity_period"
            format="yyyy年MM月dd日"
            type="date"
            placeholder="请选择时间"
          ></DatePicker>
        </FormItem>

        <FormItem label="手机号码：" prop="phonenumber">
          <Input v-model="userdata.phonenumber" placeholder="填写时请包含区号"/>
        </FormItem>

        <FormItem label="电子邮箱：" prop="email">
          <Input v-model="userdata.email" placeholder="用于紧急联络，请正确填写"/>
        </FormItem>

        <div class="pay u">
          <div class="text-title">支付方式：</div>
          <div class="text">微信支付</div>
        </div>
        <div class="pay">
          <div class="price-title">支付金额：</div>
          <div class="price">￥{{userdata.price/100}}</div>
        </div>
      </div>
      <div class="upload-box">
        <div class="img" v-if="imgdata">
          <img :src="imgdata" class="img">
        </div>
        <div class="a-upload">
          <input
            type="file"
            accept="image/png, image/jpeg, image/gif, image/jpg"
            @change="getimg"
            ref="inputer"
          >
          <div class="upload">
            <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
            <p>点击上传图片</p>
          </div>
        </div>
      </div>
      <div class="botttom-box">
        <Button type="success" class="field field_C width_max" @click="confirm('form')">确认支付</Button>
      </div>
    </Form>
  </div>
</template>

<script>
import MHeader from "components/header/header";
import { place_order } from "@/api/order";
import { pay } from "@/api/order";
import { add_order } from "@/api/order";
import { dele_order } from "@/api/order";
import { file } from "@/api/file";
// import { Wechat_pay } from "@/utils/pay";
export default {
  data() {
    return {
      title: "提交订单",
      imgdata: null,
      uploadimg: null,
      userdata: {
        _id: "", //订单id
        name: "", //真实姓名
        sex: "", //真实性别
        Date_of_birth: "", //出生日期
        ID_No: "", //身份证号码
        Passport_No: "", //护照号码
        Certificate_validity_period: "", //证件有效期
        phonenumber: "", //手机号码
        email: "", //电子邮箱
        payment_method: "", //支付方式
        price: "", //价格
        type: "" //类型
      }
      // ruleValidate: {
      //   name: [
      //     {
      //       required: true,
      //       message: "名字不能为空",
      //       trigger: "blur"
      //     }
      //   ],
      //   sex: [
      //     {
      //       required: true,
      //       message: "性别不能为空",
      //       trigger: "blur"
      //     }
      //   ],
      //   Date_of_birth: [
      //     {
      //       required: true,
      //       type: "date",
      //       message: "出生日期不能为空",
      //       trigger: "change"
      //     }
      //   ],
      //   ID_No: [
      //     {
      //       required: true,
      //       message: "身份证信息不能为空",
      //       trigger: "blur"
      //     },
      //     {
      //       type: "string",
      //       min: 8,
      //       message: "请输入正确的身份证信息",
      //       trigger: "blur"
      //     }
      //   ],
      //   Passport_No: [
      //     {
      //       required: true,
      //       message: "护照信息不能为空",
      //       trigger: "blur"
      //     },
      //     {
      //       type: "string",
      //       min: 7,
      //       message: "请输入正确的护照信息",
      //       trigger: "blur"
      //     }
      //   ],
      //   Certificate_validity_period: [
      //     {
      //       required: true,
      //       type: "date",
      //       message: "证件有效期不能为空",
      //       trigger: "change"
      //     }
      //   ],
      //   phonenumber: [
      //     {
      //       required: true,
      //       message: "手机号码不能为空",
      //       trigger: "blur"
      //     },
      //     {
      //       type: "string",
      //       min: 11,
      //       message: "请输入正确的护照信息",
      //       trigger: "blur"
      //     }
      //   ],
      //   email: [
      //     {
      //       required: true,
      //       message: "邮箱不能为空",
      //       trigger: "blur"
      //     },
      //     {
      //       type: "email",
      //       message: "请输入正确的邮箱地址",
      //       trigger: "blur"
      //     }
      //   ]
      // }
    };
  },
  mounted() {
    this.getdata();
  },
  methods: {
    getimg() {
      let imgdata = this.$refs.inputer.files[0];
      var reader = new FileReader();
      //将文件以Data URL形式读入页面
      reader.readAsDataURL(imgdata);
      reader.onload = e => {
        let img = new Image();
        img.src = e.target.result;
        console.log(img.src.length);
        img.onload = e => {
          console.log(e);
          let picdata = this.compress_pic(img);
          this.imgdata = picdata;
          this.uploadimg = this.dataURItoBlob(picdata);
          console.log(this.uploadimg);
        };
      };
    },
    //获取数据
    getdata() {
      this.userdata.price = this.$route.params.data.money;
      this.userdata._id = this.$route.params.data._id;
      this.userdata.type = this.$route.params.data.type;
      console.log(this.$route.params);
      console.log(this.userdata);
    },
    //启用加载效果
    loading() {
      this.$Spin.show();
    },
    //确定提交订单
    confirm(name) {
      this.loading();
      this.$refs[name].validate(valid => {
        if (valid) {
          let get = async () => {
            try {
              let order = await add_order(this.userdata);

              console.log(order);
              let temp = {
                order_id: order.data.order.order_id
              };
              let upload = await this.upload(temp.order_id);
              console.log(upload);
              console.log(temp);
              if (upload.data.code == "200") {
                let wechat_data = await pay(temp);
                Wechat.isInstalled(
                  installed => {
                    if (installed) {
                      var params = {
                        prepayid: wechat_data.data.backdata.prepayid, // prepay id
                        noncestr: wechat_data.data.backdata.noncestr, // nonce
                        timestamp: wechat_data.data.backdata.timestamp, // timestamp
                        sign: wechat_data.data.backdata.sign, // signed string
                        partnerid: wechat_data.data.backdata.partnerid // merchant id
                      };
                      Wechat.sendPaymentRequest(
                        params,
                        () => {
                          this.$Spin.hide();
                          this.$Modal.success({
                            title: "成功",
                            content: "支付成功"
                          });
                        },
                        reason => {
                          this.$Spin.hide();
                          this.$Modal.info({
                            title: "提示",
                            content: reason
                          });
                        }
                      );
                    } else {
                      this.$Spin.hide();
                      this.$Modal.error({
                        title: "失败",
                        content: "您尚未安装微信"
                      });
                    }
                  },
                  reason => {
                    this.$Spin.hide();
                    alert("出现错误: " + reason);
                  }
                );
              }
            } catch (error) {
              this.$Spin.hide();
              console.error(error);
              this.$Modal.error({
                title: "失败",
                content: error
              });
            }
          };
          get();
        } else {
          this.$Spin.hide();
          this.$Message.error("信息不完整");
        }
      });
    },
    upload(order_id) {
      //上传文件
      var formData = new FormData(); // 声明一个FormData对象
      var formData = new window.FormData(); // vue 中使用 window.FormData(),否则会报 'FormData isn't definded'
      formData.append("file", this.uploadimg);
      formData.append("order_id", order_id);
      return file(formData);
    },
    //压缩图片
    compress_pic(img) {
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      let initSize = img.src.length;
      let width = img.width;
      let height = img.height;
      canvas.width = width;
      canvas.height = height;
      // 铺底色
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(img, 0, 0, width, height);
      //进行最小压缩
      let ndata = canvas.toDataURL("image/jpeg", 0.5);
      console.log("*******压缩后的图片大小*******");
      console.log(ndata);
      console.log(ndata.length);
      return ndata;
    },
    // base64转成bolb对象
    dataURItoBlob(base64Data) {
      var byteString;
      if (base64Data.split(",")[0].indexOf("base64") >= 0)
        byteString = atob(base64Data.split(",")[1]);
      else byteString = unescape(base64Data.split(",")[1]);
      var mimeString = base64Data
        .split(",")[0]
        .split(":")[1]
        .split(";")[0];
      var ia = new Uint8Array(byteString.length);
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ia], { type: mimeString });
    }
  },
  components: {
    MHeader
  }
};
</script>

<style lang="stylus" scoped>
.upload-box {
  width: 100%;
  display: flex;
}

.img {
  width: 100%;
  height: 200px;
  flex: 1;
}

.a-upload {
  flex: 1;
  width: 50%;
  background-color: #fff;
  padding: 4px 10px;
  position: relative;
  cursor: pointer;
  border: 1px solid #fff;
  border-radius: 10px;
  overflow: hidden;
  display: inline-block;
}

.a-upload input {
  height: 100%;
  position: absolute;
  font-size: 100px;
  right: 0;
  top: 0;
  opacity: 0;
  cursor: pointer;
}

.upload {
  padding: 18px 0;
  text-align: center;
}

.buttom {
  margin-bottom: 20px;
}

.datecon {
  margin-left: 20px;
}

.width_max {
  width: 100%;
}

.height_max {
  height: 100%;
}

.bg_white {
  background-color: rgba(255, 255, 255, 1);
}

body {
  background-color: rgba(244, 244, 244, 1);
}

.dh {
  line-height: 100%;
  background-color: rgba(244, 244, 244, 1);
  padding-bottom: 220px;
}

.card_box {
  position: relative;
  top: 100px;
  padding: 10px;
  background-color: rgba(244, 255, 244, 0);
}

.card {
  padding: 20px;
  border: 1px solid #fff;
  border-radius: 10px;
}

.card_in {
  height: 80px;
  line-height: 80px;
  margin-bottom: 0;
}

.straight_line {
  height: 1px;
  background-color: rgba(200, 200, 200, 1);
}

.field {
  font-size: 28px;
  display: inline;
  font-family: SimHei;
}

.field_A {
  height: 80px;
  line-height: 80px;
  width: 30%;
  padding-left: 3.5%;
  color: rgba(51, 51, 51, 1);
}

.field_B {
  height: 80px;
  line-height: 80px;
  width: 70%;
  color: rgba(102, 102, 102, 1);
}

.field_C {
  text-align: center;
}

.field_D {
  height: 80px;
  line-height: 80px;
  margin-right: 3.5%;
  float: right;
  font-size: 28px;
  font-family: MicrosoftYaHeiLight;
  color: rgba(255, 119, 0, 1);
}

.field_E {
  height: 80px;
  line-height: 80px;
  margin-bottom: 0;
  display: inline;

  .field_E_in {
    display: inline;
  }
}

.select {
  float: left;
  margin-left: 50px;
  font-size: 25px;
  font-family: SimHei;
  font-weight: 400;
  color: rgba(102, 102, 102, 1);
}

.choose {
  margin-right: 25px;
  float: right;
  height: 60px;
}

.space {
  height: 10px;
}

.save_button {
  position: fixed;
  width: auto;
  left: 10px;
  right: 10px;
  bottom: 10px;
}

.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}

.pay {
  flex: 1;
  display: flex;
  font-size: 20px;

  .text-title {
    flex: 1;
  }

  .text {
    flex: 1;
    width: 100%;
    text-align: right;
  }

  .price-title {
    flex: 1;
  }

  .price {
    flex: 1;
    width: 100%;
    text-align: right;
    color: #FF7900;
  }
}

.u {
  margin-bottom: 30px;
}

.botttom-box {
  position: fixed;
  width: 100%;
  left: 0px;
  right: 10px;
  bottom: 0px;
  padding: 20px;
  background-color: #fff;
}
</style>